import { ExtractJwt, Strategy } from 'passport-jwt';
import { PassportStrategy } from '@nestjs/passport';
import { Injectable, UnauthorizedException, Logger } from '@nestjs/common';
import { UserService } from '../users/users.service';

@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
  private readonly logger = new Logger(JwtStrategy.name);

  constructor(private readonly userService: UserService) {
    super({
      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
      ignoreExpiration: false,
      secretOrKey: process.env.JWT_SECRET || 'your-secret-key-change-in-production',
    });
  }

  async validate(payload: any) {
    this.logger.log(`JWT验证负载: ${JSON.stringify(payload)}`);
    
    // 根据手机号或者ID查找用户
    let user;
    if (payload.phone) {
      // 根据手机号查找用户
      this.logger.log(`通过手机号查找用户: ${payload.phone}`);
      user = await this.userService.findByPhone(payload.phone);
    } else if (payload.id) {
      // 根据ID查找用户
      this.logger.log(`通过ID查找用户: ${payload.id}`);
      user = await this.userService.findById(payload.id);
    } else {
      this.logger.log('JWT负载中没有找到手机号或ID');
      throw new UnauthorizedException('Token格式不正确');
    }
    
    if (!user) {
      this.logger.log('JWT验证失败: 用户未找到');
      throw new UnauthorizedException('用户不存在');
    }
    
    this.logger.log(`JWT验证成功: ${JSON.stringify(user)}`);
    // 移除密码字段再返回
    const { password, ...result } = user;
    return result;
  }
}
